package com.kb.erp.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kb.erp.entity.crm.Customer;
import com.kb.erp.entity.crm.CustomerAddress;
import com.kb.erp.entity.kbidm.KbCustAddress;
import com.kb.erp.entity.kbidm.KbInvoicing;
import com.kb.erp.entity.kbidm.KbSysCust;
import com.kb.erp.mapper.sqlServer.kbidm.KbCustAddressMapper;
import com.kb.erp.mapper.sqlServer.kbidm.KbInvoicingMapper;
import com.kb.erp.mapper.sqlServer.kbidm.KbSysCustMapper;
import com.kb.erp.mapper.sqlServer.kbidm.SysUserMapper;
import com.kb.erp.service.KBIDMService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
@DS("KBIDM")
public class KBIDMServiceImpl extends ServiceImpl<KbCustAddressMapper, KbCustAddress> implements KBIDMService {
    @Resource
    private CrmServiceImpl crmService;
    @Resource
    private KbInvoicingMapper invoicingMapper;
    @Resource
    private KbSysCustMapper sysCustMapper;
    @Resource
    private KbCustAddressMapper custAddressMapper;
    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    @DSTransactional
    public void crmCustInfo2IDM(String code) {
        //后续根据更新时间查询最近2天的数据进行更新 todo
        List<Customer> customerList = crmService.queryCustomerByCode(code);
        if (CollectionUtils.isNotEmpty(customerList)) {
            for (Customer customer : customerList) {
                //基本信息
                KbSysCust kbSysCust = new KbSysCust();
                String custId = UUID.randomUUID().toString();
                BeanUtils.copyProperties(customer, kbSysCust);

                kbSysCust.setFId(custId);
                kbSysCust.setFRecid(customer.getRecid());
                kbSysCust.setSysuserid(customer.getSysuserid());
                kbSysCust.setIsactivate(1);
                kbSysCust.setFDeletemark(0);

                //先查询kbidm方是否有值，有则更新，无则插入
                    KbSysCust customerById = sysCustMapper.queryCustomerById(customer.getRecid());
                if (Objects.isNull(customerById)) {
                    //调新增用户接口 生成客户用户
                    HashMap<String, Object> paramMap = new HashMap<>();
                    Map<String,String> headers = new HashMap<>();
                    headers.put("Content-Type", "application/json");

                    String custUserId = UUID.randomUUID().toString();
                    paramMap.put("account", "kb"+customer.getCustcode());
                    paramMap.put("Id",custUserId );
                    paramMap.put("PassWord","123456" );
                    paramMap.put("realName", customer.getCustname());
                    paramMap.put("nickName", customer.getCustnickname());
                    paramMap.put("mobilePhone", customer.getCusttel());
                    paramMap.put("email", customer.getCustemail());
                    paramMap.put("crmid", customer.getRecid());
                    String url = "http://192.168.51.12:5000/api/AccountAPI/CRM2IDMUser";
                    HttpResponse response = HttpRequest.post(url)
                            .body(JSONUtil.toJsonStr(paramMap))
                            //.addHeaders(headers)
                            .execute();

                    JSONObject jsonObject = JSONObject.parseObject(response.body());
                    //用户和客户关系
                    kbSysCust.setFUserid(custUserId);
                    sysCustMapper.insert(kbSysCust);
                } else {
                    kbSysCust.setFId(customerById.getFId());
                    custId = customerById.getFId();
                    sysCustMapper.updateById(kbSysCust);
                }
                //开票抬头信息
                KbInvoicing kbInvoicing = new KbInvoicing();
                BeanUtils.copyProperties(customer, kbInvoicing);

                kbInvoicing.setTaxpayerNumber(customer.getTariff());
                kbInvoicing.setInvoiceHeader(customer.getBillingcompany());
                kbInvoicing.setDepositBank(customer.getBank());
                kbInvoicing.setMailingaddress(customer.getBillingadd());
                kbInvoicing.setBankAccount(customer.getAccount());
                kbInvoicing.setStatus(1);


                kbInvoicing.setFCustid(custId);
                kbInvoicing.setFId(UUID.randomUUID().toString());
                kbInvoicing.setFDeletemark(0);
                kbInvoicing.setFRecid(customer.getRecid());
                //先查询kbidm方是否有值，有则更新，无则插入
                KbInvoicing invoiceById = invoicingMapper.queryInvoiceById(customer.getRecid());
                if (Objects.isNull(invoiceById)) {
                    invoicingMapper.insert(kbInvoicing);
                } else {
                    kbInvoicing.setFId(invoiceById.getFId());
                    invoicingMapper.updateById(kbInvoicing);
                }
                //地址信息
                List<CustomerAddress> addressList = crmService.queryCustAddress(customer.getRecid());
                if (CollectionUtils.isNotEmpty(addressList)) {
                    Integer i = 0;
                    for (CustomerAddress customerAddress : addressList) {
                        KbCustAddress kbCustAddress = new KbCustAddress();
                        BeanUtils.copyProperties(customerAddress, kbCustAddress);

                        kbCustAddress.setFId(UUID.randomUUID().toString());
                        kbCustAddress.setFCustid(custId);
                        kbCustAddress.setContactNumber(customerAddress.getTel());
                        kbCustAddress.setRemark(customerAddress.getNote());
                        kbCustAddress.setFRecid(customerAddress.getRecid());
                        kbCustAddress.setIsAcquiesce(0);
                        kbCustAddress.setIsAcquiesce(1);

                        kbCustAddress.setFDeletemark(0);
                        kbCustAddress.setDetailedAddress(customerAddress.getAddress());
                        //先查询kbidm方是否有值，有则更新，无则插入
                        KbInvoicing queryAddressById = custAddressMapper.queryAddressById(customerAddress.getRecid());
                        if (Objects.isNull(queryAddressById)) {
                            custAddressMapper.insert(kbCustAddress);
                        } else {
                            kbCustAddress.setFId(queryAddressById.getFId());
                            custAddressMapper.updateById(kbCustAddress);
                        }
                        i++;
                    }

                }
            }
        }
    }
}
